package zuk.clipvietfun;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import zuk.clipvietfun.clip.Clip;
import zuk.clipvietfun.clip.ClipAdapter;
import zuk.clipvietfun.clip.MPagerAdapter;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.os.StrictMode;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.view.Menu;
import android.widget.RelativeLayout;

import com.google.ads.AdRequest;
import com.google.ads.AdView;
import com.viewpagerindicator.TabPageIndicator;


public class Main extends FragmentActivity {
	ClipAdapter adapter;
	List<Clip> listClips = new ArrayList<Clip>();
	ViewPager pager;
	PagerAdapter mPagerAdapter;
	TabPageIndicator mIndicator;
	int count = 0;
	File dir;
	Context context = getBaseContext();
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		
		AdView ad = (AdView) findViewById(R.id.adView);
		ad.loadAd(new AdRequest());
		if (android.os.Build.VERSION.SDK_INT > 9) {
			StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
			StrictMode.setThreadPolicy(policy);
		}
		dir = new File(getBaseContext().getCacheDir() + "/data");
		DirAndFile.deleteDir(dir); 
		RelativeLayout load_ly = (RelativeLayout)findViewById(R.id.load_ly);
		new LoadScreen(dir,load_ly).execute();
		
		mPagerAdapter = new MPagerAdapter(getSupportFragmentManager(),settab);
		pager = (ViewPager) super.findViewById(R.id.viewpager);
		pager.setAdapter(mPagerAdapter);
	
		mIndicator = (TabPageIndicator)findViewById(R.id.indicator);
		mIndicator.setViewPager(pager);
		
		
		
	}

	
	private Handler settab =new Handler(new Callback() {
		public boolean handleMessage(Message msg) {
			pager.setCurrentItem(msg.arg1+1);
			return true;
		}
	});


	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) 
	{
		if (keyCode == KeyEvent.KEYCODE_BACK ) {
			if(pager.getCurrentItem()!=0){
				pager.setCurrentItem(0);
				return false;
			}else{
				this.finish();
			}
			return true;
		}
		return super.onKeyDown(keyCode, event);    
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
	}
	@Override
	protected void onDestroy() {
		DirAndFile.deleteDir(dir); 
		super.onDestroy();
	}
}
